<template>
	<section>
		<!-- 工具条：高级查询 + 添加 -->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="queryParams">
				<el-form-item>
					<el-input v-model="queryParams.keyword" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="advancedQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!-- 列表展示 -->
    <el-table :data="pageParams.departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" label="序号" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="120" sortable>
      </el-table-column>
      <el-table-column prop="name" label="部门" width="120" sortable>
      </el-table-column>
      <el-table-column prop="dirPath" label="路径" width="120" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="120" sortable>
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.state==0">正常</span>
          <span style="color: red" v-else-if="scope.row.state==1">停用</span>
          <span style="color: darkslategray" v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="经理" width="120">
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="120" sortable>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

		<!-- 工具条：批量删除 + 分页栏 -->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="queryParams.pageSize" :total="pageParams.totals" :current-page="queryParams.currentPage" style="float:right;">
			</el-pagination>
		</el-col>

		<!-- 新增或修改的模态框 -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="0">启用</el-radio>
            <el-radio class="radio" :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理">
          <el-select v-model="saveForm.manager" value-key="id" placeholder="请选择">
            <el-option
                v-for="emp in managers"
                :label="emp.username"
                :value="emp">
              <span style="float: left">{{ emp.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ emp.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent"
                       :options="deptTree"
                       :props="{
                                checkStrictly: true,
                                label: 'name',
                                value: 'id'
                              }"
                       clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
	</section>
</template>
<script>
  export default {
		data() {
			return {
			  //分页参数：分页列表 + 分页栏所需数据
        pageParams:{
          departments: [],    //分页列表中：data
          totals: 0           //总页数：分页栏中显示
        },

        //定义查询参数：分页查询 + 高级查询
        queryParams:{
          pageSize: 5,      //分页查询参数：每页显示的条数 or 分页栏中显示
          currentPage: 1,   //分页查询参数：当前页 or 分页栏中显示
          keyword: ''       //高级查询参数：关键字查询
        },

				listLoading: false,
				sels: [],//列表选中列

        title:"保存", //添加和修改的模态框的标题
				saveFormVisible: false,//编辑界面是否显示
				saveLoading: false,
        saveFormRules: {
          name: [
            { required: true, message: '请输入名称', trigger: 'blur' }
          ],
          sn: [
            { required: true, message: '请输入编号', trigger: 'blur' }
          ]
        },
        //编辑界面数据
        saveForm: {
          id: null,
          sn: null,
          name: null,
          state: 0, //默认启用
          manager: null,
          parent: null,
        },
        // 所有的经理
        managers : [],
        // 部门树
        deptTree:[]
			}
		},
		methods: {
			handleCurrentChange(val) {
			  // console.log(val);
				this.queryParams.currentPage = val;
				this.getDepartments();
			},
      // 高级查询方法
      advancedQuery() {
        this.queryParams.currentPage = 1;
        this.getDepartments();
      },
			//获取部门列表
			getDepartments() {
				this.listLoading = true; //忙等框
        // 发送请求
        this.$http.post("/department", this.queryParams,)
            .then(res => {
              // 讲数据的总条数赋值给totals
              this.pageParams.totals = res.data.totals;
              this.pageParams.departments = res.data.data;
              // console.log(res.data.data);
              // 关闭忙等框
              this.listLoading = false;
				    }).catch(res => {
				      this.$message.error("系统错误");
        });
			},
      // 是否为最后一页的最后一条数据
      isLastPage() {
        // 根据总的数据条数total和一页显示的数据条数，得到总页数
        let lastPage = this.pageParams.totals % this.queryParams.pageSize;
        // 判断当前页是否是最后一页且为最后一条数据
        if (lastPage == 1) {
          this.queryParams.currentPage--;
        }
      },
			// 删除
			handleDel: function (index, row) {
			  // 先判断是否为当前页最后一条数据
			  this.isLastPage();
        this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					// 将当行的id拼接到url上
          let para = "/department/"  + row.id;
					this.$http.delete(para).then((res) => {
						this.listLoading = false;
						if (res.data.success) {
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.getDepartments();
						} else {
              this.$message({
                message: '删除失败',
                type: 'error'
              })
            }}).catch(res => {
              this.$message.error("系统错误,请稍后重试");
          });
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
			  // 获取部门经理
			  this.getManager();
			  // 获取部树
        this.getDeptTree();
        // 加载忙等框
				this.saveFormVisible = true;
				// 设置标题为修改
				this.title = "修改";
				// 获取数据
				this.saveForm = Object.assign({}, row);
				// 获取当前行的diePath
        let dirPath = row.dirPath;
        // 分割数组
        let idArr = dirPath.split("/");
        // 设置一个空数组
        let arr = [];
        // 遍历将数组的值传入
        for(let i=1;i<idArr.length-1;i++){
          let id = parseInt(idArr[i]);
          arr[i-1] = id;
        }
        // 赋值为aveForm.parent
        this.saveForm.parent = arr;
			},
			//显示新增界面
			handleAdd: function () {
        // 获取部门经理
			  this.getManager();
        // 获取部树
        this.getDeptTree();
        this.title = "添加";
				this.saveFormVisible = true;
				// 重置数据
				this.saveForm = {
          id: null,
          sn: null,
          name: null,
          state: 1, //默认启用
          manager: {
            username : null,
          },
          parent: {
            name: null,
          }
				};
			},
      // 所有经理
      getManager() {
			  // 发送请求
        this.$http.get("/employee").then(res => {
          this.managers = res.data;
        }).catch(res => {
          this.$message.error("系统错误,请稍后重试");
        })
      },
      // 所有部门
      getDeptTree() {
        // 发送请求
        this.$http.get("/department/depttree").then(res => {
          this.deptTree = res.data;
        }).catch(res => {
          this.$message.error("系统错误,请稍后重试");
        })
      },
			//编辑
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
              let arr = this.saveForm.parent;
              this.saveForm.parent = {id:arr[arr.length-1]};
              let para = Object.assign({}, this.saveForm);
              if(!para.id){ // 如果是添加
                // 获取总页数
                let totalPage = this.pageParams.totals % this.queryParams.pageSize == 0 ? Math.floor(this.pageParams.totals / this.queryParams.pageSize) : Math.floor(this.pageParams.totals / this.queryParams.pageSize + 1);
                // 总数量是每页显示的条数的倍数
                if(this.pageParams.totals % this.queryParams.pageSize == 0){
                  this.queryParams.currentPage = totalPage + 1;
                  alert(this.queryParams.currentPage)
                }else{
                  this.queryParams.currentPage = totalPage;
                }
              }
							this.$http.put("/department", para).then((res) => {
								this.saveLoading = false;
                if (res.data.success) {
                  this.$message({
                    message: '操作成功',
                    type: 'success'
                  });
                  this.getDepartments();
                } else {
                  this.$message({
                    message: '操作失败',
                    type: 'error'
                  })
                }
								this.$refs['saveForm'].resetFields();
								this.saveFormVisible = false;
								this.getDepartments();
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
        // console.log(sels);
      },
			//批量删除
			batchRemove: function () {
				let ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					// let ids = { ids: id};
          // axios获取数据的格式都是res.data,然后再获取
					this.$http.patch("/department", ids, {headers: {
              'Content-Type': 'application/json'
            }}).then(res => {
            this.listLoading = false;
					  if (res.data.success){
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.advancedQuery();
            }
          }).catch(res => {
            this.$message({
              message: '删除失败',
              type: 'error'
            });
          })
				}).catch(() => {

				});
			}
		},
		mounted() {
		  //页面一加载 - 获取分页数据
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>